import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';

import 'package:provider/provider.dart';
import 'package:system_theme/system_theme.dart';
import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:flutter_acrylic/flutter_acrylic.dart' as flutter_acrylic;
import 'package:url_strategy/url_strategy.dart';

import 'screens/colors.dart';
import 'screens/forms.dart';
import 'screens/inputs.dart';
import 'screens/mobile.dart';
import 'screens/others.dart';
import 'screens/settings.dart';
import 'screens/typography.dart';

import 'theme.dart';

const String appTitle = 'Fluent UI Showcase for Flutter';

late bool darkMode;

/// Checks if the current environment is a desktop environment.
/// 检查是否为桌面应用
bool get isDesktop {
  if (kIsWeb) return false;
  return [
    TargetPlatform.windows,
    TargetPlatform.linux,
    TargetPlatform.macOS,
  ].contains(defaultTargetPlatform);
}

void main() async {
  //确保初始化完成
  WidgetsFlutterBinding.ensureInitialized();

  setPathUrlStrategy();

  // The platforms the plugin support (01/04/2021 - DD/MM/YYYY):
  //   - Windows
  //   - Web
  //   - Android
  // 如平台是Windows或是安卓,或是web系统
  if (defaultTargetPlatform == TargetPlatform.windows ||
      defaultTargetPlatform == TargetPlatform.android ||
      kIsWeb) {
    // 检查是否位黑夜模式
    darkMode = await SystemTheme.darkMode;
    //载入系统配色
    await SystemTheme.accentInstance.load();
  } else {
    //否则默认为黑夜模式
    darkMode = true;
  }
  //如果不是网页,而是Windows或linux,就初始化一种配色
  if (!kIsWeb &&
      [TargetPlatform.windows, TargetPlatform.linux]
          .contains(defaultTargetPlatform)) {
    await flutter_acrylic.Acrylic.initialize();
  }
  //启动主界面
  runApp(const MyApp());
  //如果是桌面
  if (isDesktop) {
    // 配置窗口初始化完成时的回调
    doWhenWindowReady(() {
      final win = appWindow;
      win.minSize = const Size(410, 540);
      win.size = const Size(755, 545);
      win.alignment = Alignment.center;
      win.title = appTitle;
      win.show();
    });
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AppTheme(),
      builder: (context, _) {
        final appTheme = context.watch<AppTheme>();
        return FluentApp(
          title: appTitle,
          themeMode: appTheme.mode,
          debugShowCheckedModeBanner: false,
          initialRoute: '/',
          routes: {'/': (_) => const MyHomePage()},
          theme: ThemeData(
            accentColor: appTheme.color,
            brightness: appTheme.mode == ThemeMode.system
                ? darkMode
                    ? Brightness.dark
                    : Brightness.light
                : appTheme.mode == ThemeMode.dark
                    ? Brightness.dark
                    : Brightness.light,
            visualDensity: VisualDensity.standard,
            //设置焦点图案的光圈效果粗细
            focusTheme: FocusThemeData(
              glowFactor: is10footScreen() ? 2.0 : 0.0,
            ),
          ),
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool value = false;
  // 默认选中的导航页面
  int index = 0;

  final colorsController = ScrollController();
  final settingsController = ScrollController();

  @override
  void dispose() {
    colorsController.dispose();
    settingsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final appTheme = context.watch<AppTheme>();
    // 带有导航面板的窗口
    return NavigationView(
      appBar: NavigationAppBar(
        // height: !kIsWeb ? appWindow.titleBarHeight : 31.0,
        title: () {
          if (kIsWeb) return const Text(appTitle);
          //如果不是web系统,就插入一个窗口移动部件
          return MoveWindow(
            child: const Align(
              alignment: Alignment.centerLeft,
              child: Text("${appTitle}"),
            ),
          );
        }(),
        actions: kIsWeb
            ? null
            : MoveWindow(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: const [Spacer(),Text('===='), WindowButtons()],
                ),
              ),
      ),
      // 导航面板的布局
      pane: NavigationPane(
        //配置要选中的导航页面
        selected: index,
        //页面切换时自动更新索引
        onChanged: (i) => setState(() => index = i),
        // 顶部的logo图标布局
        header: Container(
          height: kOneLineTileHeight,
          // 配置图标左右两侧的间距
          padding: const EdgeInsets.symmetric(horizontal: 10.0),
          child: const FlutterLogo(
            style: FlutterLogoStyle.horizontal,
            size: 90,
          ),
        ),
        //配置导航面板的显示风格
        displayMode: appTheme.displayMode,


        //配置导航高亮条
        // indicatorBuilder: ({
        //   required BuildContext context,
        //   required NavigationPane pane,
        //   Axis? axis,
        //   required Widget child,
        // }) {
        //   if (pane.selected == null) return child;
        //   axis ??= Axis.horizontal;
        //   assert(debugCheckHasFluentTheme(context));
        //   final theme = NavigationPaneTheme.of(context);
        //   // 根据高亮条配置构建显示
        //   switch (appTheme.indicator) {
        //     // 宽高亮条
        //     case NavigationIndicators.end:
        //       return EndNavigationIndicator(
        //         index: pane.selected!,
        //         offsets: () =>
        //             pane.effectiveItems.getPaneItemsOffsets(pane.paneKey),
        //         sizes: pane.effectiveItems.getPaneItemsSizes,
        //         child: child,
        //         color: theme.highlightColor,
        //         curve: theme.animationCurve ?? Curves.linear,
        //         axis: axis,
        //       );
        //
        //     //  窄高亮条
        //     case NavigationIndicators.sticky:
        //       return NavigationPane.defaultNavigationIndicator(
        //         context: context,
        //         axis: axis,
        //         pane: pane,
        //         child: child,
        //       );
        //
        //     default:
        //       return NavigationIndicator(
        //         index: pane.selected!,
        //         offsets: () =>
        //             pane.effectiveItems.getPaneItemsOffsets(pane.paneKey),
        //         sizes: pane.effectiveItems.getPaneItemsSizes,
        //         child: child,
        //         color: theme.highlightColor,
        //         curve: theme.animationCurve ?? Curves.linear,
        //         axis: axis,
        //       );
        //   }
        // },


        // 导航菜单配置
        items: [
          // It doesn't look good when resizing from compact to open
          // PaneItemHeader(header: Text('菜单导航目录')),
          //菜单项配置
          PaneItem(
            icon: const Icon(FluentIcons.checkbox_composite),
            title: const Text('Inputs'),
          ),
          PaneItem(
            icon: const Icon(FluentIcons.text_field),
            title: const Text('Forms'),
          ),
          //分隔线
          PaneItemSeparator(),
          PaneItem(
            icon: const Icon(FluentIcons.color),
            title: const Text('Colors'),
          ),
          PaneItem(
            icon: const Icon(FluentIcons.plain_text),
            title: const Text('Typography'),
          ),
          PaneItem(
              icon: const Icon(FluentIcons.cell_phone),
              title: const Text('Mobile')),
          PaneItem(
            icon: Icon(
              appTheme.displayMode == PaneDisplayMode.top
                  ? FluentIcons.more
                  : FluentIcons.more_vertical,
            ),
            title: const Text('Others'),
          ),
        ],


        // 插入搜索输入框
        // autoSuggestBox: AutoSuggestBox<String>(
        //   controller: TextEditingController(),
        //   // 配置搜索框的输入联想词汇
        //   items: const ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
        // ),
        // // compact显示风格下的搜索框icon图标
        // autoSuggestBoxReplacement: const Icon(FluentIcons.search),

        // 底部的设置面板
        footerItems: [
          // 设置上配置分隔线
          PaneItemSeparator(),
          PaneItem(
              icon: const Icon(FluentIcons.settings),
              title: const Text('Settings')),
        ],
      ),
      //配置导航菜单对应的页面
      content: NavigationBody(
          index: index,
          //配置导航菜单对应的7个页面
          children: [
        // 表单按钮控件
        const InputsPage(),
        // 表单输入控件
        const Forms(),
        // 色块展示页面
        ColorsPage(controller: colorsController),
        //  文章排版页
        const TypographyPage(),
        //  手机页面布局
        const Mobile(),
        //  提示面板进度条标签页的布局
        const Others(),
        //  设置页面
        Settings(controller: settingsController),
      ]),
    );
  }
}
// 操作系统的窗口按钮
class WindowButtons extends StatelessWidget {
  const WindowButtons({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasFluentTheme(context));
    assert(debugCheckHasFluentLocalizations(context));
    final ThemeData theme = FluentTheme.of(context);
    final buttonColors = WindowButtonColors(
      iconNormal: theme.inactiveColor,
      iconMouseDown: theme.inactiveColor,
      iconMouseOver: theme.inactiveColor,
      mouseOver: ButtonThemeData.buttonColor(
          theme.brightness, {ButtonStates.hovering}),
      mouseDown: ButtonThemeData.buttonColor(
          theme.brightness, {ButtonStates.pressing}),
    );
    final closeButtonColors = WindowButtonColors(
      mouseOver: Colors.red,
      mouseDown: Colors.red.dark,
      iconNormal: theme.inactiveColor,
      iconMouseOver: Colors.red.basedOnLuminance(),
      iconMouseDown: Colors.red.dark.basedOnLuminance(),
    );
    return Row(children: [
      // 配置控件提示文字
      Tooltip(
        message: FluentLocalizations.of(context).minimizeWindowTooltip,
        // 最小化按钮
        child: MinimizeWindowButton(colors: buttonColors),
      ),
      Tooltip(
        message: FluentLocalizations.of(context).restoreWindowTooltip,
        child: WindowButton(
          colors: buttonColors,
          iconBuilder: (context) {
            if (appWindow.isMaximized) {
              // 窗口复位按钮
              return RestoreIcon(color: context.iconColor);
            }
            // 最大化按钮
            return MaximizeIcon(color: context.iconColor);
          },
          onPressed: appWindow.maximizeOrRestore,
        ),
      ),
      Tooltip(
        message: FluentLocalizations.of(context).closeWindowTooltip,
        // 关闭窗口按钮
        child: CloseWindowButton(colors: closeButtonColors),
      ),
    ]);
  }
}
